package job.manager.db.dao;

import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import job.manager.db.ec.UserGroupsEB;
import job.manager.db.ec.UsersEB;

/**
 *  DAO class is responsible for communcation with the
 *  database regarding usergroups.
 */

public class UserGroupsDAO {

    EntityManager em;

    public UserGroupsDAO(EntityManager em) {
        this.em = em;
    }

        public int update(UserGroupsEB groups) {
        if (groups != null) {
            UserGroupsEB g = em.merge(groups);
            em.persist(g);
            if (em.contains(g)) {
                return 1;
            }
        }
        return 0;
    }

    public int insert(UserGroupsEB groups) {
        if (groups != null) {
            em.persist(groups);

            if (em.contains(groups)) {
                return 1;
            }
        }
        return 0;
    }

    public int delete(UserGroupsEB groups) {
        if (groups != null) {
            UserGroupsEB g = em.merge(groups);

            em.remove(g);

            if (!em.contains(g)) {
                return 1;
            }
        }
        return 0;
    }

    public Collection<UserGroupsEB> getAllUserGroups() {
        Query q = em.createNamedQuery("UserGroupsEB.findAll");
        return q.getResultList();
    }

    public Collection<UsersEB> getAllUsersByGroup(String name) {

        Query q = em.createNamedQuery("UserGroupsEB.findByGroupName");
        q.setParameter("name", name);
        UserGroupsEB g = (UserGroupsEB)q.getSingleResult();
        

        return g.getUsersEBCollection();
    }

    public UserGroupsEB getUserGroupByPk(Integer pk) {
        return em.find(UserGroupsEB.class, pk);
    }

}
